package com.atguigu.gmall.product.controller;


import com.atguigu.gmall.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping("admin/product")
@RestController
@Api("文件上传")
public class UploadFileController {

    @Value("${img.url}")
    private String imgUrl;

    @PostMapping("fileUpload")
    @ApiOperation("文件上传")
    public Result fileUpload(MultipartFile file) throws  Exception{
        System.out.println(file.getSize());
        System.out.println(file.getName());//file  Form Data Key值
        //file.getBytes()

        //扩展名
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());


        String path = ClassUtils.getDefaultClassLoader().getResource("tracker.conf").getPath();
        //流：只能读取绝对路径  不认识相对路径
        ClientGlobal.init(path);
        //2:上传连接请求  找跟踪器
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        //3:连接存储节点Storage
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,null);
        //4:上传图片
        String file_id = storageClient1.upload_file1(file.getBytes() , ext, null);
        return Result.ok(imgUrl +file_id);//硬编码问题

    }

}
